<?php

require_once "process_file.php";

require_once "vendor/steelywing/Chinese.php";
require_once "vendor/codesniffer/Tokens.php";
require_once "vendor/codesniffer/Tokenizer.php";
require_once "vendor/codesniffer/Comment.php";
require_once "vendor/codesniffer/JS.php";
require_once "vendor/codesniffer/TokenizerException.php";

define('PHP_CODESNIFFER_VERBOSITY', 1);


use PHP_CodeSniffer\Tokenizers\JS;

function strip_one_js_file($from_file, $to_file)
{
    $buffer = file_get_contents($from_file);
    // already minified files, skip them
    $to_skip = array(
        '.min.js', 'highcharts.js', 'qqapi.custom.js', 
        '/qb.js', 'jpeg.encoder.basic.js', 'userapp_swfobject.js'
    );
    $should_minify = true;

    foreach ($to_skip as $skip) {
        if (ends_with($from_file, $skip)) {
            logging\debug("skip stripping js %s", $from_file);
            $should_minify = false;
            break;
        }
    }

    if ($should_minify) {
        logging\debug("processing js %s", $from_file);
        $eol = detect_eol($buffer);
        $js = new JS($buffer, null, $eol);
        $tokens = $js->getTokens();
        $newstr = "";
        $block_comment = "";
        $in_block_comment = false;
        foreach ($tokens as $token) {
            $content = $token["content"];
            if ($token["type"] !== "T_COMMENT") {
                $newstr .= $content;
            } else {
                if (starts_with($content, "//")) {
                    $newstr .= $eol;
                }   
                if (starts_with($content, "/*")) {
                    $block_comment = "";
                    $in_block_comment = true;
                }
                if ($in_block_comment) {
                    $block_comment .= $content;
                }
                if (ends_with($content, "*/")) {
                    $in_block_comment = false;
                    if (str_contains($block_comment, "[Discuz!]")) {
                        $newstr .= $block_comment;
                    }
                }
            }
        }   
        $buffer = ltrim($newstr);
    }

    mkdir_of_file($to_file);
    file_put_contents($to_file, $buffer);
}

function js_file_condition($fi)
{
    return strtolower($fi->getExtension()) == 'js';
}

function strip_all_js_files($from_path, $to_path)
{
    logging\info("processing JavaScript files");
    process_all_files_with_condition($from_path, $to_path, 'js_file_condition', 'strip_one_js_file');
}

?>